package top.lingkang.fas.admin.web.impl;

import java.util.Random;

/**
 * 数学运算验证码生成器
 * 生成两个随机个位数的加减乘除运算，确保结果为正整数
 */
public class MathCaptchaGenerator {
    private static final Random random = new Random();
    private static final char[] OPERATORS = {'+', '-', '*', '/'};

    // 禁止实例化
    private MathCaptchaGenerator() {
    }

    /**
     * 生成验证码对象
     *
     * @return 包含问题和答案的验证码对象
     */
    public static Captcha generate() {
        int num1, num2;
        char operator;
        int result;

        // 循环直到生成有效的运算组合
        do {
            num1 = random.nextInt(10); // 0-9
            num2 = random.nextInt(10); // 0-9
            operator = OPERATORS[random.nextInt(OPERATORS.length)];

            switch (operator) {
                case '+':
                    result = num1 + num2;
                    break;
                case '-':
                    // 确保减法结果为正
                    if (num1 < num2) {
                        int temp = num1;
                        num1 = num2;
                        num2 = temp;
                    }
                    result = num1 - num2;
                    break;
                case '*':
                    result = num1 * num2;
                    break;
                case '/':
                    // 确保除法有效且结果为整数
                    while (num2 == 0 || num1 % num2 != 0) {
                        num1 = random.nextInt(10);
                        num2 = random.nextInt(10);
                    }
                    result = num1 / num2;
                    break;
                default:
                    throw new IllegalStateException("Unexpected operator: " + operator);
            }
        } while (result < 0); // 确保结果为非负整数
        if (operator == '*')
            operator = 'x';
        else if (operator == '/')
            operator = '÷';
        String question = String.format(" %d %c %d =? ", num1, operator, num2);
        return new Captcha(question, result);
    }


    // 测试示例
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Captcha captcha = generate();
            System.out.println("问题: " + captcha.getQuestion());
            System.out.println("答案: " + captcha.getAnswer());
            System.out.println("---");
        }
    }
}